# -*- coding: utf8 -*-
import os
import jinja2
import webapp2
import json

from game_template import *

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'])


class GameIdHandler(webapp2.RequestHandler):
    def get_game_template(self):
        game_id = int(self.request.get("id"))
        pin = int(self.request.get("pin"))
        try:
            game = GameTemplate.get_by_id(game_id, pin)
        except WrongPincodeError:
            self.error(403)
            self.response.write('ERROR 403: You have no access'
                                ' to game  %s' % game_id)
            return None
        if game is None:
            self.error(404)
            self.response.write('ERROR 404: Game %d not found' % game_id)
            return None
        return game


class CreateGameForm(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('create_game.html')
        self.response.write(template.render())


def parse_names_text_area(string):
    return [s.strip() for s in string.split("\n")]


class ProcessCreatingGame(webapp2.RequestHandler):
    def post(self):
        names_string = self.request.get("names")
        words_string = self.request.get("words")
        time = self.request.get("time")
        before_out = self.request.get("before_out")
        skip = self.request.get("skip")

        names = parse_names_text_area(names_string)
        words = words_string.split()
        game_id = GameTemplate.get_new_id()

        self.settings = Settings()
        self.settings.time_per_round_sec = int(time)
        self.settings.time_before_out_sec = int(before_out)
        self.settings.skip_words_per_round = int(skip)

        gt = GameTemplate(players=names, words=words, id_=game_id,
                          settings=self.settings)
        gt.put()
        self.redirect("/edit_game.html?game_key=%s" % gt.key.urlsafe())


class EditGameForm(webapp2.RequestHandler):
    def get(self):
        game_key = ndb.Key(urlsafe=self.request.get("game_key"))
        game = game_key.get()
        template = JINJA_ENVIRONMENT.get_template('edit_game.html')
        self.response.write(template.render(
            {"players": '\n'.join(game.players),
             "words": '\n'.join(game.words),
             "time": game.settings.time_per_round_sec,
             "last_seconds_time": game.settings.time_before_out_sec,
             "skip_words_limit": game.settings.skip_words_per_round,
             "id": game.id_,
             "pin_code": game.pin_code}))


class ProcessEditingGame(GameIdHandler):
    def post(self):
        gt = self.get_game_template()
        if gt is None:
            return
        names_string = self.request.get("names")
        words_string = self.request.get("words")
        time = int(self.request.get("time"))
        before_out = int(self.request.get("before_out"))
        skip = int(self.request.get("skip"))
        names = parse_names_text_area(names_string)
        words = words_string.split()
        gt.players = names
        gt.words = words
        gt.settings.time_per_round_sec = time
        gt.settings.time_before_out_sec = before_out
        gt.settings.skip_words_per_round = skip
        gt.put()
        self.redirect("/edit_game.html?game_key=%s" % gt.key.urlsafe())


class GetGameTemplateJson(GameIdHandler):
    def get(self):
        game_id = self.request.get("game_id")
        pin = self.request.get("pin")
        try:
            game = GameTemplate.get_by_id(int(game_id), int(pin))
        except WrongPincodeError:
            self.error(403)
            self.response.write('ERROR 403: You have no access to game ' +
                                game_id)
            return
        if game is None:
            self.error(404)
            self.response.write('ERROR 404: Game ' + game_id + ' not found')
            return
        self.response.write(game.make_json())


class AddPlayerToGameForm(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('add_player_to_game.html')
        self.response.write(template.render())


class ProcessAddingPlayer(GameIdHandler):
    def post(self):
        gt = self.get_game_template()
        if gt is None:
            return
        name = self.request.get("name")
        words_string = self.request.get("words")
        words = words_string.split()
        gt.players.append(name)
        gt.words += words
        gt.put()
        self.redirect("/main_menu.html")


class ChooseGameByIDForm(webapp2.RequestHandler):
    def get(self):
        template = JINJA_ENVIRONMENT.get_template('choose_game_by_id.html')
        self.response.write(template.render())


class ProcessChoosingGameById(GameIdHandler):
    def post(self):
        gt = self.get_game_template()
        if gt is not None:
            self.redirect("/edit_game.html?game_key=%s" % gt.key.urlsafe())
